import { Cell } from "./Cell";
import { ICell } from "./ICell";

export class CellGroup {
    constructor() {
    }

    private aliveCells: ICell[] = []
    private tempDic: any = {};
    private tempAliveKeys: any = {};

    public markNextAroundCells(cell: ICell) {
        const positions = cell.getAroundPosition();

        const aroundCount = positions.filter(t => this.tempAliveKeys[t.key]).length;

        if (aroundCount < 2 || aroundCount > 3) {
            this.tempDic[cell.key] = -1;
        }
        else {
            this.tempDic[cell.key] = 100;
        }

        positions.forEach(t => {
            if (!this.tempDic[t.key]) {
                this.tempDic[t.key] = 1;
            }
            else if (this.tempDic[t.key] == -1) {
                return;
            }
            else{
                this.tempDic[t.key] = this.tempDic[t.key] + 1;
            }
        });
    }

    public getNextCells(): ICell[] {
        this.tempDic = {};
        this.aliveCells.forEach(t => {
            this.markNextAroundCells(t);
        })

        const aliveCells: ICell[] = [];
        for (let property in this.tempDic) {
            if (this.tempDic[property] == 3 || this.tempDic[property] >= 100) {
                const xy = property.split(',');
                aliveCells.push(new Cell(parseInt(xy[0]), parseInt(xy[1])));
            }
        }
        return aliveCells;
    }

    public moveToNext() {
        this.aliveCells = this.getNextCells();
        this.tempAliveKeys = {};
        this.aliveCells.forEach(t => this.tempAliveKeys[t.key] = true);
    }

    public addAliveCell(x: number, y: number) {
        const key = x + ',' + y
        const cells = this.aliveCells.filter(t => t.key == key);
        if (cells.length > 0) {
            this.aliveCells = this.aliveCells.filter(t => t.key != key);
        }
        else {
            this.aliveCells.push(new Cell(x, y));
        }
        this.tempAliveKeys = {};
        this.aliveCells.forEach(t => this.tempAliveKeys[t.key] = true);
    }

    public clearAliveCell() {
        this.aliveCells = [];
        this.tempAliveKeys = {};
    }

    public getAliveCells(): ICell[] {
        return this.aliveCells;
    }
}